package light.mvc.service.wxn.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import light.mvc.dao.BaseDaoI;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.wxn.WeiConfigVO;
import light.mvc.service.wxn.ConfigServiceI;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import light.mvc.model.wxn.WeiConfigBO;

@Service
public class ConfigServiceImpl implements ConfigServiceI {

	@Autowired
	private BaseDaoI<WeiConfigBO> ConfigDao;

	@Override
	public void add(WeiConfigVO r) {
		WeiConfigBO t = new WeiConfigBO();
		t.setApp_id(r.getApp_id());
		t.setApp_secret(r.getApp_secret());
		ConfigDao.save(t);
	}

	@Override
	public void delete(Long id) {
		WeiConfigBO t = ConfigDao.get(WeiConfigBO.class, id);
		ConfigDao.delete(t);
	}

	@Override
	public void edit(WeiConfigVO r) {
		WeiConfigBO t = ConfigDao.get(WeiConfigBO.class, r.getId());
		t.setApp_id(r.getApp_id());
		t.setApp_secret(r.getApp_secret());
		ConfigDao.update(t);
	}

	@Override
	public WeiConfigVO get(Long id) {
		WeiConfigBO t = ConfigDao.get(WeiConfigBO.class, id);
		WeiConfigVO r = new WeiConfigVO();
		r.setId(t.getId());
		r.setApp_id(t.getApp_id());
		r.setApp_secret(t.getApp_secret());
		return r;
	}

	@Override
	public List<WeiConfigVO> dataGrid(WeiConfigVO config, PageFilter ph) {
		List<WeiConfigVO> ul = new ArrayList<WeiConfigVO>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from WeiConfigBO t ";
		List<WeiConfigBO> l = ConfigDao.find(hql + whereHql(config, params) + orderHql(ph), params, ph.getPage(), ph.getRows());
		for (WeiConfigBO t : l) {
			WeiConfigVO u = new WeiConfigVO();
			BeanUtils.copyProperties(t, u);
			ul.add(u);
		}
		return ul;
	}

	@Override
	public Long count(WeiConfigVO config, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from WeiConfigBO t ";
		return ConfigDao.count("select count(*) " + hql + whereHql(config, params), params);
	}

	private String whereHql(WeiConfigVO config, Map<String, Object> params) {
		String hql = "";
		if (config != null) {
			hql += " where 1=1 ";
			if (config.getApp_id() != null) {
				hql += " and t.app_id like :app_id";
				params.put("app_id", "%%" + config.getApp_id() + "%%");
			}
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

}
